package com.conduit.comnands;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conduit.enums.ResultCode;

public class InstallCommand extends Command {

	public InstallCommand() {
		commandSyntax = "install\\s{2,}(.*)";
	}
	
	@Override
	public void executeWithArgs(String args) {
		// validate command's syntax
		if (!args.matches(commandSyntax)) {
			setResult("Error in Command's syntax (\"" + args + "\")");
			setResultCode(ResultCode.Error);
			return;
		}
		Matcher matcher = Pattern.compile(commandSyntax).matcher(args);
		if (matcher.find()) {
			ProcessBuilder probuilder = new ProcessBuilder(matcher.group(1)); 
			Process process;
			try {
				process = probuilder.start();
			

			// Read out dir output
			InputStream is = process.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line;
			//TODO check error code
//			while ((line = br.readLine()) != null) {
//				System.out.println(line);
//			}
//			// Wait to get exit value
//			// TODO validate installation from CLI or exit value
//			try {
//				int exitValue = process.waitFor();
//				System.out.println("\n\nExit Value is " + exitValue);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public String getCommandName() {
		return "Install Product";
	}

}
